package com.icesoft.framework.core.util;

import org.apache.commons.lang3.SystemUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 路径工具类
 */
@SuppressWarnings("unused")
public class PathUtil {

	public static final String RESOURCE_PREFIX = "uploadFiles/";

	/**
	 * 文件上传根路径，本地绝对路径
	 */
	protected static String uploadRootPath;

	/**
	 * 项目文件保存根目录，输出目录，target目录，
	 * (D:/icesoft/target/)
	 */
	public static String getProjectRootPath() {
		String localPath = SystemUtils.USER_DIR + "/" + getRelativeRootPath();
		localPath = localPath.replace("\\", "/");
		return localPath;
	}

	/**
	 * 项目根目录，相对路径，target目录，
	 */
	public static String getRelativeRootPath() {
		return "target/";
	}

	public static void setUploadPath(String path) {
		uploadRootPath = path.replace("\\", "/");
	}

	/**
	 * 增加后缀 “/”
	 */
	public static String appendPathEnd(String path) {
		if (path.endsWith("/")) {
			return path;
		}
		return path + "/";
	}

	/**
	 * 增加前缀 “/”
	 */
	public static String appendPathStart(String path) {
		if (path.startsWith("/")) {
			return path;
		}
		return "/" + path;
	}

	/**
	 * 得到上传文件夹的路径,绝对路径
	 * (D:/icesoft/target/uploadFiles/)
	 */
	public static String getRootUploadPath() {
		if (uploadRootPath == null) {
			uploadRootPath = getProjectRootPath() + RESOURCE_PREFIX;
		}

		return uploadRootPath;
	}

	/**
	 * 获取项目路径
	 */
	public static String getClasspath() {
		String path = (Thread.currentThread().getContextClassLoader().getResource("") + "../../")
				.replace("file:/", "").replace("%20", " ").trim();
		if (path.indexOf(":") != 1) {
			path = File.separator + path;
		}
		return path;
	}

	/**
	 * 获取target下源文件路径
	 */
	public static String getClassResources() {
		String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")))
				.replaceAll("file:/", "").replaceAll("%20", " ").trim();
		if (path.indexOf(":") != 1) {
			path = File.separator + path;
		}
		return path;
	}

	public static File getPathFile(String path) {
		return new File(PathUtil.getProjectRootPath() + path);
	}

	/**
	 * 获取jar包中或是外部文件路径流，以外部文件为准
	 */
	public static InputStream getPathInputStream(String path) throws IOException {
		InputStream inputStream;
		File file = new File(PathUtil.getProjectRootPath() + path);
		if (file.exists()) {
			inputStream = new FileInputStream(file);
		} else {
			ClassPathResource cr = new ClassPathResource(path);
			if (!cr.exists()) {
				throw new IOException("文件不存在:" + path);
			}
			inputStream = cr.getInputStream();
		}
		return inputStream;
	}
}
